<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.location_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        &lt;!&ndash; <extended-attribute-config @changeTable="changeTable"></extended-attribute-config> &ndash;&gt;-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ row }" slot="status">
        <el-tag :class="row.status === 0 ? 'successTag' : 'dangerTag'">{{ row.status === 0 ? '是' : '否' }}</el-tag>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getSelectList, getList, getDetail, add, update, remove } from '@/api/admin/location';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import ExtendedAttributeConfig from '../../components/extendedAttributeConfig/extendedAttributeConfig.vue';
export default {
  name: 'AdminLocation',
  components: {
    userTableConfig,
    ExtendedAttributeConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'ADMIN_LOCATION',
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      selectData: [],
      code: '00',
      searchLabelWidth: 100,
      option: {
        height: 'calc(100vh - 360px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        selection: true,
        dialogClickModal: false,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '名称',
            prop: 'name',
            search: true,
            order: 1,
            width: 150,
            rules: [
              {
                required: true,
                message: '请输入地址名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '国家',
            prop: 'countryName',
            width: 150,
            display: false
          },
          {
            label: '国家',
            prop: 'country',
            order: 3,
            type: 'select',
            cascader: ['province'],
            value: '00',
            dicData: [
              {
                label: '中华人民共和国',
                value: '00'
              }
            ],
            hide: true,
            rules: [
              {
                required: true,
                message: '请输入国家',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '省份',
            prop: 'provinceName',
            width: 150,
            display: false
          },
          {
            label: '省份',
            prop: 'province',
            order: 5,
            type: 'select',
            cascader: ['city'],
            // row: true,
            props: {
              label: 'name',
              value: 'code'
            },
            dicFlag: false,
            dicUrl: '/api/blade-system/region/select?code={{key}}',
            hide: true,
            rules: [
              {
                required: true,
                message: '请输入省份',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '城市',
            prop: 'cityName',
            display: false
          },
          {
            label: '城市',
            prop: 'city',
            type: 'select',
            order: 7,
            dicFlag: false,
            dicUrl: '/api/blade-system/region/select?code={{key}}',
            props: {
              label: 'name',
              value: 'code'
            },
            hide: true,
            rules: [
              {
                required: true,
                message: '请输入城市',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '详细地址1',
            prop: 'location1',
            order: 9,
            rules: [
              {
                required: true,
                message: '请输入详细地址',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '详细地址2',
            prop: 'location2',
            order: 10
          },
          {
            label: '详细地址3',
            prop: 'location3',
            order: 11
          },
          {
            label: '详细地址4',
            prop: 'location4',
            order: 12
          },
          {
            label: '邮编',
            prop: 'postCode',
            order: 2,
            hide: true,
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^[0-9]{6}$/;
                  if (value && !reg.test(value)) {
                    callback(new Error('请输入六位数的邮编'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '经度',
            prop: 'latitude',
            order: 4,
            hide: true,
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/;
                  if (value && !reg.test(value)) {
                    callback(new Error('请输入-180~180的数字，可以保留六位小数'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '纬度',
            prop: 'longitude',
            order: 6,
            hide: true,
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/;
                  if (value && !reg.test(value)) {
                    callback(new Error('请输入-90~90的数字，可以保留六位小数'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '启用',
            prop: 'status',
            order: 8,
            type: 'switch',
            value: 0,
            align: 'center',
            dicData: [
              {
                label: '否',
                value: 1
              },
              {
                label: '是',
                value: 0
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择状态',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      optionsList: [{ label: '列表', value: 'option' }]
    };
  },
  provide() {
    return {
      optionsList: this.optionsList,
      crud: this.$refs.crud
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.location_add, false),
        viewBtn: this.vaildData(this.permission.location_view, false),
        delBtn: this.vaildData(this.permission.location_delete, false),
        editBtn: this.vaildData(this.permission.location_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });

    this.getSelectData(this.code);
  },
  methods: {
    rowSave(row, done, loading) {
      console.log(row);
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    getSelectData(code) {
      getSelectList(code)
        .then((res) => {
          // debugger
          this.selectData = res.data.data;
          // console.log(res.data.data, 'resresas')
        })
        .catch((err) => {
          this.message(err);
        });
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // [] || dataListTable
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    changeTable(data) {
      this[data.optionName].column = [...this[data.optionName].column, ...data.column];
      console.log(this[data.optionName].column);
      this.$refs.crud.refreshTable();
    }
  }
};
</script>

<style></style>
